package com.res.share.service.impl;

import com.res.share.service.ImageService;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


@Service
public class ImageServiceImpl implements ImageService {

    private static final Logger LOGGER= LoggerFactory.getLogger(ImageService.class);

    //上传路径
    @Value("${file.doc-dir}")
    private  String UPLOAD_PATH;


    @Override
    public String uploadImage(MultipartFile image, HttpServletRequest request) throws Exception{
        String name = image.getOriginalFilename();
        InputStream inputStream = image.getInputStream();
        // 获得客户端发送请求的完整url
        String url = request.getRequestURL().toString();
        // 获得去除接口前的url
//        String urlVal = url.replace("/uploadImage", "");
        // 目录路径
        Path directory = Paths.get(UPLOAD_PATH);
        // 判断目录是否存在，不存在创建
        if (!Files.exists(directory)) {
            Files.createDirectories(directory);
        }
        // 判断文件是否存在,存在删除
        if (Files.exists(directory.resolve(name))) {
            File file = new java.io.File(UPLOAD_PATH + "/" + name);
            file.delete();
        }
        // 拷贝文件
        Files.copy(inputStream, directory.resolve(name));
        // url路径
        // String path = serverConfig.getUrl() + "/" + UPLOAD_PATH + "/" + name;
//        String path = urlVal + "/" + UPLOAD_PATH + "/" + name;
        String path ="/" + UPLOAD_PATH + "/" + name;
        return path;
    }
}
